package com.yaoweigroup.community.ui.base;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions.Builder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.util.Bimp;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.FileUtils;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.LoginUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;
import com.yaoweigroup.community.util.Utils;

/**
 * 我的个人信息
 * 
 * @author xi
 * 
 */
public class MyProfileActivity extends Activity implements OnClickListener {

	private RelativeLayout left_rl;

	private ImageView icon_iv;
	private TextView edit_tv;
	private EditText name_et;
	private EditText sex_et;
	private EditText real_et;
	private TextView birth_et;
	private EditText yiliao_et;
	private EditText id_et;
	private EditText email_et;
	private EditText address_et;
	private EditText sb_et;
	private Button update_btn;
	private RelativeLayout birth_rl;

	private TextView test_tv;
	private EditText phone_et;

	public final int UPDATE_SUCCESS = 0x2210;
	public final int UPDATE_FAIL = UPDATE_SUCCESS + 1;
	public final int SUBMIT = UPDATE_SUCCESS + 2;
	public final int NEED_LOGIN = UPDATE_SUCCESS + 3;
	public final int DETAIL_FAIL = UPDATE_SUCCESS + 4;
	public final int DETAIL_SUCCESS = UPDATE_SUCCESS + 5;

	private Dialog dialog;

	private static final int TAKE_PICTURE = 0;
	private static final int RESULT_LOAD_IMAGE = 1;
	private static final int CUT_PHOTO_REQUEST_CODE = 2;
	private float dp;
	private String imgUrl;
	private SharePreferenceUtil util;
	private ObjectMapper mapper;
	private boolean isTrue = false;
	private Calendar calendar;
	private DatePickerDialog dateDialog;
	private EditText remark_et;
	public String image = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAoAJYDASIAAhEBAxE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w82pX3hu2Gv21vDqBBFxBbt8iENwMhm7Y71sBFDMwUBm6kDk1FS/O7WsEPhVytb3SGESyTgLIxKb8KQM4x70URm2m2RGAKwUsI3jwVGcfhRXPFzsrNM1fLfUkmV3khVQ4QNuZlbGMdAR3Bp1w6RwO0jlExgsOozxxRRVVPdjKQo6tIjtYI4lMiO8hlAJdzkkY4qXa/nbvM/d7cbMd/XNFFOCXKrCbd2VZtKsJC8rafbzSbeA8YPToBnpU9ukNvDFCkccAI+WJMAA9TgCiihpR1Q+ZyVmyaqscNvvkhRn2omxosnaAec/WiilO146b/wCT/wAgjsyeLywgSMgqny4BzjHanK6vnawODg4OcH0ooqk9hNFQIXuJ4pJQryAMvlDDBQcZzjrUVxDb6m0cVzpwkjKN88q4KZ4OPQ8Doc0UVit7ef6/8E0u1qhDt0p4wJ5Xt3wqxSHd5Y7kMcsfoSfb0q4/7/zIf3seMfOvGe/BoopRk3UlT6afigl8Kl1EMXmTys0ZQ7NiyB+SDycDtg1Mi7EVck4GMk5J+tFFdCikZN3GLCqTGRSRkYKjhSfXHr71JRRTSS2C4z95538Hlbffdu/wooooSA//2Q==";

	private EditText identity_et;
	private EditText credit_et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mapper = new ObjectMapper();
		util = new SharePreferenceUtil(this, Constant.prf);
		dp = getResources().getDimension(R.dimen.dp);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_my_profile);

		identity_et = (EditText) findViewById(R.id.identity_et);
		credit_et = (EditText) findViewById(R.id.credit_et);
		dialog = DialogUtil.createWaitDialog(this, "数据修改中...");
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);

		icon_iv = (ImageView) findViewById(R.id.icon_iv);
		edit_tv = (TextView) findViewById(R.id.edit_tv);
		edit_tv.setOnClickListener(this);
		name_et = (EditText) findViewById(R.id.name_et);
		sex_et = (EditText) findViewById(R.id.sex_et);
		real_et = (EditText) findViewById(R.id.real_et);
		birth_et = (TextView) findViewById(R.id.birth_et);
		yiliao_et = (EditText) findViewById(R.id.yiliao_et);
		id_et = (EditText) findViewById(R.id.id_et);
		email_et = (EditText) findViewById(R.id.email_et);
		address_et = (EditText) findViewById(R.id.address_et);
		sb_et = (EditText) findViewById(R.id.sb_et);
		update_btn = (Button) findViewById(R.id.update_btn);
		update_btn.setOnClickListener(this);
		birth_et.setOnClickListener(this);
		calendar = Calendar.getInstance();
		dateDialog = new DatePickerDialog(this,
				new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker dp, int year, int month,
							int dayOfMonth) {
						birth_et.setText(year + "-" + month + "-" + dayOfMonth);
					}
				}, calendar.get(Calendar.YEAR), // 传入年份
				calendar.get(Calendar.MONTH), // 传入月份
				calendar.get(Calendar.DAY_OF_MONTH) // 传入天数
		);
		Bitmap newBitmp = BitmapFactory.decodeResource(getResources(),
				R.drawable.test_icon);
		Bitmap bitmap = Utils.toRoundCorner(newBitmp, 30);
		icon_iv.setImageBitmap(bitmap);
		icon_iv.setOnClickListener(this);
		birth_rl = (RelativeLayout) findViewById(R.id.birth_rl);
		remark_et = (EditText) findViewById(R.id.remark_et);
		phone_et = (EditText) findViewById(R.id.phone_et);
		// birth_rl.setOnClickListener(this);
	}

	private UserInfo user;

	@Override
	protected void onResume() {
		user = (UserInfo) util.loadObject("user");
		if (user != null) {
			name_et.setText(user.getUsername());
			sex_et.setText(user.getSex());
			real_et.setText(user.getRealname());
			birth_et.setText(user.getBirth());
			yiliao_et.setText(user.getMediano());
			id_et.setText(user.getIdentity());
			email_et.setText(user.getEmail());
			address_et.setText(user.getAddress());
			sb_et.setText(user.getSocialID());
			phone_et.setText(user.getPhone());
			remark_et.setText(user.getRemark());
			credit_et.setText(user.getIntegral() + "");
			if (user.getIsign() == 0) {
				identity_et.setText("否");
			} else {
				identity_et.setText("是");
			}
			if (user.getIsign() == 0) {
				edit_tv.setVisibility(View.VISIBLE);
			} else {
				edit_tv.setVisibility(View.GONE);
			}
			displayHead(R.drawable.test_icon, Urls.imgUrl + user.getIconPath(),
					icon_iv);
		}
		super.onResume();
	}

	private boolean isEdit = false;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.update_btn:
			// uploadImg();
			updateInfo();
			break;
		case R.id.birth_et:
			LogUtil.d("wxf", "birth click");
			if (isEdit) {
				dateDialog.show();
			}
			break;
		case R.id.edit_tv:
			if (update_btn.getVisibility() == View.VISIBLE) {
				update_btn.setVisibility(View.GONE);
				// view
				isEdit = false;
				edit_tv.setText("编辑");
				eidtMode(isEdit);
			} else {
				update_btn.setVisibility(View.VISIBLE);
				// edit
				isEdit = true;
				edit_tv.setText("编辑中");
				eidtMode(isEdit);
			}
			break;
		case R.id.icon_iv:
			isTrue = false;
			new PopupWindows(this, icon_iv);
			break;
		}

	}

	private void eidtMode(boolean isEdit) {
		boolean edit = false;
		if (isEdit) {
			edit = true;
		} else {
			edit = false;
		}
		// name_et.setEnabled(edit);
		sex_et.setEnabled(edit);
		real_et.setEnabled(edit);
		// birth_et.setEnabled(edit);
		email_et.setEnabled(edit);
		yiliao_et.setEnabled(edit);
		id_et.setEnabled(edit);
		address_et.setEnabled(edit);
		sb_et.setEnabled(edit);
		remark_et.setEnabled(edit);
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			dialog.dismiss();
			switch (msg.what) {
			case UPDATE_FAIL:
				if (user.getIconPath() != null) {
					displayHead(R.drawable.test_icon,
							Urls.imgUrl + user.getIconPath(), icon_iv);
				} else {
					Bitmap newBitmp = BitmapFactory.decodeResource(
							getResources(), R.drawable.test_icon);
					Bitmap bitmap = Utils.toRoundCorner(newBitmp, 30);
					icon_iv.setImageBitmap(bitmap);
				}
				Toast.makeText(MyProfileActivity.this, "修改失败", 500).show();
				break;
			case UPDATE_SUCCESS:
				if (bitmap != null) {
					Bitmap newBit = Utils.toRoundCorner(bitmap, 180);
					icon_iv.setImageBitmap(newBit);
				}
				Toast.makeText(MyProfileActivity.this, "修改成功", 500).show();
				break;
			case SUBMIT:
				uploadImg();
				break;
			case LoginUtil.LOGIN_FAIL:
				Toast.makeText(MyProfileActivity.this, "修改失败", 500).show();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				if (isUpdateInfo) {
					updateInfo();
				} else {
					uploadImg();
				}
				break;
			case NEED_LOGIN:
				LoginUtil.isLoginSuccess(MyProfileActivity.this, handler,
						mapper);
				break;
			case DETAIL_FAIL:
				dialog.dismiss();
				Toast.makeText(MyProfileActivity.this, "修改失败!", 500).show();
				break;
			case DETAIL_SUCCESS:
				util.saveObject(user, "user");
				dialog.dismiss();
				Toast.makeText(MyProfileActivity.this, "修改成功!", 500).show();
				break;
			}

		};
	};

	public void displayHead(int defaultIcon, String url, ImageView view) {
		Builder builder = new DisplayImageOptions.Builder();
		builder.displayer(new RoundedBitmapDisplayer(180));
		// builder.showImageOnFail(defaultIcon);
		// builder.showImageForEmptyUri(defaultIcon);
		builder.cacheInMemory(true);
		builder.cacheOnDisk(true);
		// builder.showImageOnLoading(defaultIcon);

		DisplayImageOptions displayImageOptions = builder.build();
		ImageLoader.getInstance().displayImage(url, view, displayImageOptions);
	}

	private boolean isUpdateInfo = false;

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			// ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
			// R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent i = new Intent(
							// 相册
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(i, RESULT_LOAD_IMAGE);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	private String path = "";
	private Uri photoUri;

	public void photo() {
		try {
			Intent openCameraIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);

			String sdcardState = Environment.getExternalStorageState();
			String sdcardPathDir = android.os.Environment
					.getExternalStorageDirectory().getPath() + "/tempImage/";
			File file = null;
			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				// 有sd卡，是否有myImage文件夹
				File fileDir = new File(sdcardPathDir);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 是否有headImg文件
				file = new File(sdcardPathDir + System.currentTimeMillis()
						+ ".JPEG");
			}
			if (file != null) {
				path = file.getPath();
				photoUri = Uri.fromFile(file);
				openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(openCameraIntent, TAKE_PICTURE);
			}

		} catch (Exception e) {
			LogUtil.e("wxf", "photo=" + e.toString());
		}
	}

	private void startPhotoZoom(Uri uri) {
		try {
			// 获取系统时间 然后将裁剪后的图片保存至指定的文件夹
			SimpleDateFormat sDateFormat = new SimpleDateFormat(
					"yyyyMMddhhmmss");
			String address = sDateFormat.format(new java.util.Date());
			if (!FileUtils.isFileExist("")) {
				FileUtils.createSDDir("");

			}
			imgUrl = FileUtils.SDPATH + address + ".JPEG";
			Uri imageUri = Uri.parse("file:///sdcard/formats/" + address
					+ ".JPEG");
			final Intent intent = new Intent("com.android.camera.action.CROP");
			// 照片URL地址
			intent.setDataAndType(uri, "image/*");

			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 480);
			intent.putExtra("outputY", 480);
			// 输出路径
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			// 输出格式
			intent.putExtra("outputFormat",
					Bitmap.CompressFormat.JPEG.toString());
			// 不启用人脸识别
			intent.putExtra("noFaceDetection", false);
			intent.putExtra("return-data", false);
			startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);

		} catch (IOException e) {
			LogUtil.e("wxf", "startPhotoZoom=" + e.toString());
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (resultCode == -1) {// 拍照
				startPhotoZoom(photoUri);
			}
			break;
		case RESULT_LOAD_IMAGE:
			if (resultCode == RESULT_OK && null != data) {// 相册返回
				Uri uri = data.getData();
				if (uri != null) {
					startPhotoZoom(uri);
				}
			}
		case CUT_PHOTO_REQUEST_CODE:
			if (resultCode == RESULT_OK && null != data) {// 裁剪返回
				bitmap = Bimp.getLoacalBitmap(imgUrl);
				bitmap = Bimp.createFramedPhoto(480, 480, bitmap,
						(int) (dp * 1.6f));

				if (bitmap != null && isTrue) {
					icon_iv.setImageBitmap(Utils.toRoundCorner(bitmap, 180));
					bitmapToString(Utils.compressBmpFromBmp(bitmap));

				}
				isTrue = true;
			}
			break;
		}

	}

	private String userId = "";
	private String userame = "";
	private String imgstr = "";
	private Bitmap bitmap;

	private void bitmapToString(final Bitmap bitmap) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				if (bitmap != null) {
					imgstr = Utils.bitmaptoString(bitmap);
					handler.sendEmptyMessage(SUBMIT);
				}

			}
		}).start();
	}

	private String uploadStr = null;

	private void uploadImg() {

		UserInfo user = (UserInfo) util.loadObject("user");
		if (user == null)
			return;
		dialog.show();
		Map<String, String> params = new HashMap<String, String>();
		imgstr = imgstr.replaceAll("[\\t\\n\\r]", "");
		params.put("Uid", user.getUid());
		params.put("imgstr", imgstr);
		StringEntity enity = null;
		try {
			uploadStr = mapper.writeValueAsString(params);
			enity = new StringEntity(uploadStr, "UTF-8");
		} catch (Exception e) {

		}
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams param = new RequestParams();
		param.setContentType("application/json;charset=utf-8");
		param.setBodyEntity(enity);
		param.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.updateUserImg, param,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						String result = responseInfo.result;
						LogUtil.d("wxf", "result=" + result);
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(UPDATE_SUCCESS);
							} else if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else {
								handler.sendEmptyMessage(UPDATE_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(UPDATE_FAIL);
							LogUtil.e("wxf", e.toString());
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error + "," + msg);
						handler.sendEmptyMessage(UPDATE_FAIL);
					}

				});

	}

	private void updateInfo() {
		isUpdateInfo = true;
		String name = name_et.getText().toString();
		String sex = sex_et.getText().toString();
		String real = real_et.getText().toString();
		String birth = birth_et.getText().toString();
		String email = email_et.getText().toString();
		String yiliao = yiliao_et.getText().toString();
		String id = id_et.getText().toString();
		String address = address_et.getText().toString();
		String sb = sb_et.getText().toString();
		user = (UserInfo) util.loadObject("user");
		user.setBirth(birth);
		user.setSex(sex);
		user.setEmail(email);
		user.setIdentity(id);
		user.setMediano(yiliao);
		user.setSocialID(sb);
		user.setAddress(address);
		if (!(sex.equals("男") || sex.equals("女"))) {
			Toast.makeText(MyProfileActivity.this, "性别内容必须为男 或 女", 500).show();
			return;
		}
		if (user == null)
			return;
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		JsonUtil util = new JsonUtil();
		util.add("Uid", user.getUid());
		util.add("RealName", real);
		util.add("MedicalID", yiliao);
		util.add("SocialID", sb);
		util.add("Sex", sex);
		util.add("Address", address);
		util.add("cardno", id);
		util.add("Email", email);
		util.add("Birthday", birth);
		util.add("remark", remark_et.getText().toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(util.toString(), "UTF-8");
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		RequestParams params = new RequestParams();
		params.setContentType("application/json;charset=utf-8");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.updateUserInfo, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						String result = responseInfo.result;
						LogUtil.d("wxf", "result=" + result);
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(DETAIL_SUCCESS);
							} else if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else {
								handler.sendEmptyMessage(DETAIL_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(DETAIL_FAIL);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", msg);
						handler.sendEmptyMessage(DETAIL_FAIL);
					}

				});
	}
}
